package com.are.inventario;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class MarcasActivity extends Activity {
	
private ProgressDialog progressDialog;
private String[] items;
	
	private final Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.obj != null) {
				CreateFileXML((String)msg.obj);			
			}
			progressDialog.dismiss();
	    }
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.marcas_activity);
		ListView listView1 = (ListView) findViewById(R.id.listView1);
		listView1.setOnItemClickListener(new OnItemClickListener() {

    		public void onItemClick(AdapterView<?> av, View v, int position,
    				long id) {
		        	String marca = items[position];
		        	Intent intent = new Intent();
					intent.putExtra("marca", marca);
					setResult(RESULT_OK, intent);
					finish();
    		}
    	}); 

		File file = new File("/data/data/com.are.inventario/files/marcas.xml");
		if (!file.exists()) {
			System.out.println("No existe el fichero");
			progressDialog = ProgressDialog.show(
	    			MarcasActivity.this,
	    			"", 
	    			"Por favor espere mientras se cargan los datos...", 
	    			true);
			new Thread(new Runnable() {
				public void run() {
					Message msg = progressHandler.obtainMessage();
					msg.obj = ReadXMLServer();
					progressHandler.sendMessage(msg);
				}
			}).start();
		} else { // Si existe el fichero
			System.out.println("Existe el fichero");
			Mostrar();

		}
		
		

	}
	
	public void CreateFileXML(String strxml) {
		OutputStreamWriter fout= null;
		
		try {
			fout=  new OutputStreamWriter(
			            openFileOutput("marcas.xml", Context.MODE_PRIVATE));
			fout.write(strxml);
			fout.flush();
			Mostrar();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		
	}

	public void Mostrar() {
		System.out.println("Leyendo Items");
		ListView listView1 = (ListView) findViewById(R.id.listView1);

		items = ReadXML();
		for (int x=0; x < items.length; x++) {
			System.out.println(items[x]);
		}

		AdaptadorPais adaptador = new AdaptadorPais(this, items);

		listView1.setAdapter(adaptador);

	}

	public String[] ReadXML() {
		InputStream is = null;
		String marcas[] = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			System.out.println("Leyendo archivo");
			is = new FileInputStream(
					"/data/data/com.are.inventario/files/marcas.xml");
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse(is);

			Element root = dom.getDocumentElement();
			// Localizamos todos los elementos <item>
			NodeList items = root.getElementsByTagName("pais");
			// Recorremos la lista de noticias
			marcas = new String[items.getLength()];
			for (int i = 0; i < items.getLength(); i++) {
				// Obtenemos la noticia actual
				Node item = items.item(i);
				// Obtenemos la lista de datos de la noticia actual
				NodeList nodos = item.getChildNodes();
				// Procesamos cada dato de la noticia
				
				for (int j = 0; j < nodos.getLength(); j++) {
					Node dato = nodos.item(j);
					String etiqueta = dato.getNodeName();
					if (etiqueta.equals("codigo")) {

					} else if (etiqueta.equals("descripcion")) {
						
						marcas[i] = dato.getFirstChild().getNodeValue();
						System.out.println(marcas[i]);
					}
				}

			}

		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return marcas;
	}

	public String  ReadXMLServer() {
		String result = "";
		try {
			URL Url = new URL("http://siscos.fcr.com.co:8080/AreApp/XmlMarcas");

			HttpURLConnection urlConnection = (HttpURLConnection) Url
					.openConnection();
			// urlConnection.setDoOutput(true);
			InputStream in = new BufferedInputStream(
					urlConnection.getInputStream());

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					in, "utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			result = sb.toString();
			System.out.println(result);

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;

	}

}
